package org.layuiframework.stereotype.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.layuiframework.stereotype.security.bean.LoginUser;
import org.layuiframework.stereotype.security.impl.CacheServiceImpl;
import org.layuiframework.stereotype.vo.ResultVo;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码过滤器
 */
@Component
public class VerifyCodeFilter extends GenericFilterBean {
    private String defaultFilterProcessUrl = "/index/login";

    @Resource
    CacheServiceImpl cache ;

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        if ("POST".equalsIgnoreCase(request.getMethod()) && request.getRequestURI().endsWith(defaultFilterProcessUrl)) {
            ResultVo responseEntity = new ResultVo((Object) null);
            ObjectMapper mapper = new ObjectMapper();
            responseEntity.setData(null);
            response.setStatus(200);
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            // 验证码验证
            String requestCaptcha = request.getParameter("vercode");
            if(!StringUtils.hasLength(requestCaptcha)){
                responseEntity.setCode(400);
                responseEntity.setMsg("验证码不能为空");//验证码不能为空
                response.getWriter().write(mapper.writeValueAsString(responseEntity));
                return;
            }
            String crc = request.getParameter("crc");
            LoginUser loginUser = new LoginUser();
            loginUser.setClientId(crc);
            loginUser.setVerifyCode(requestCaptcha);
            LoginUser user =  cache.getVerifyCode(loginUser);
            if (user == null || user.getVerifyCode() ==null || !user.getVerifyCode().toLowerCase().equals(requestCaptcha.toLowerCase())) {
                responseEntity.setCode(400);
                responseEntity.setMsg("验证码错误"); //验证码错误
                response.getWriter().write(mapper.writeValueAsString(responseEntity));
                return ;
            }
            cache.removeVerifyCode(loginUser);//清除失效验证码
        }
        chain.doFilter(request, response);
    }

}
